<template>
  <div>
    <common-header>
      <template v-slot:title> 我的购物车 </template>
    </common-header>
    <el-divider></el-divider>
    <div class="frame">
      <el-row>
        <el-col
          style="
            width: 1190px;
            height: 72px;
            margin: 100px, 30px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #e6e6e6;
          "
        >
          <span class="all-goods" style="margin: 10px"
            >购物车(全部:{{ total }})</span
          >
          <span
            >已选商品<em class="price">{{ totalSum }}</em
            >件</span
          >
          <span>
            合计(不含运费):<em class="price">{{ totalPrice }}</em>
          </span>
          <el-button
            type="danger"
            round
            style="margin-right: 10px"
            @click="goSettle"
            >结算</el-button
          >
        </el-col>
        <el-col>
          <el-table
            :data="tableData"
            height="620"
            style="width: 100%"
            ref="multipleTable"
            tooltip-effect="dark"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column label="商品信息" width="400" align="center">
              <template slot-scope="scope">
                <div>
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="scope.row.productSkus.skuImg"
                    :fit="fits"
                  />
                </div>
                <div>
                  {{ scope.row.skuProps }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="productSkus.sellPrice"
              label="单价"
              align="center"
            />
            <el-table-column label="数量" align="center" width="300">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.cartNum"
                  :min="1"
                  :max="scope.row.productSkus.stock"
                  @change="changNum(scope.row)"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="金额" align="center">
              <template slot-scope="scope">
                <span
                  >￥{{
                    scope.row.cartNum * scope.row.productSkus.sellPrice
                  }}</span
                >
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <span
                  @click="delUser(scope.row.cartId)"
                  style="cursor: pointer"
                >
                  删除
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col style="height: 72px; display: flex; align-items: center">
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import CommonHeader from "../components/CommonHeader.vue";
import http from "@/utils/request";
export default {
  components: {
    CommonHeader,
  },
  data() {
    return {
      fits: "contain",
      number: 0,
      sum: 0,
      multipleSelection: [],
      total: 0,
      totalPrice: 0,
      totalSum: "0",
      tableData: [],
      UserId:0,
    };
  },

  mounted() {
    this.getToken();
  },

  methods: {
    getToken() {
      let accessToken = this.$cookies.get("access_token");
      let ts = accessToken.split("."); // 根据 . 拆分jwt字符串
      let payload = JSON.parse(
        decodeURIComponent(
          escape(window.atob(ts[1].replace(/-/g, "+").replace(/_/g, "/")))
        )
      );
      let sub = payload.sub; // 获取到用户名
      http
        .post("/shopping/user", {
          userName: sub,
        })
        .then((res) => {
          this.userId = res.data.data.userId;
          this.goto(this.userId);
        });
    },

    goto(userId) {
      http.get(`/shopping/${userId}`).then((res) => {
        this.tableData = res.data.data;
        let b = this.tableData.map((v) => v.cartid);
        this.total = b.length;
      });
    },

    goSettle() {
      if (this.totalPrice == 0) {
        this.$message({
          message: "请选择商品",
        });
      } else {
        let l = this.multipleSelection.map((v) => v.skuId);
        let parObj = JSON.stringify(l)
        window.sessionStorage.setItem('currentID', parObj)
        this.$router.push({
          path: "/settle",
          query: {id:this.userId}
        });
      }
    },

    delUser(cartId) {
      http.delete(`/shopping/${cartId}`);
      this.$router.go(0);
    },

    changNum(row) {
      http
        .post(`/shopping`, {
          cartId: row.cartId,
          cartNum: row.cartNum,
        })
        .then((res) => {
          let oneCart = res.data.data;
          let a = oneCart.cartId;
          let c = oneCart.cartNum;
          let b = oneCart.productSkus.sellPrice;
          let d = this.multipleSelection.map((v) => v.cartId);
          if (this.totalSum != 0) {
            for (let i = 0; i < d.length; i++) {
              if (a == d[i]) {
                if (this.number < c) {
                  this.totalPrice = this.totalPrice - (c - 1) * b + c * b;
                } else {
                  this.totalPrice = this.totalPrice - b;
                }
              }
            }

            this.number = c;
          }
        });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (val == null) {
        this.totalPrice = 0;
        this.totalSum = 0;
      } else {
        let b = val.map((v) => {
          return v.cartNum * v.productSkus.sellPrice;
        });
        this.sum = 0;
        for (let i = 0; i < b.length; i++) {
          this.sum = b[i] + this.sum;
        }
        this.totalPrice = this.sum;
        this.totalSum = b.length;
      }
    },
  },
};
</script>

<style scoped>
.item {
  display: flex;
}
.item .item-pic {
  width: 60px;
  height: 60px;
}

.item .item-title {
  padding-left: 8px;
  width: 180px;
}
.settle-panel {
  position: fixed;
  width: 100%;
  bottom: 0;
  z-index: 1000;
}
.settle-panel .checkall-btn {
  position: absolute;
  top: 8px;
}
.settle-panel .del-all {
  position: absolute;
  left: 70px;
  top: 10px;
}
.settle-panel .settle-btn {
  position: absolute;
  top: -5px;
  right: 100px;
}
.all-goods {
  color: #000;
  font-size: 18px;
  font-weight: 600;
}
.frame {
  border: 1px solid #e6e6e6;
  width: 1190px;
  border-radius: 20px;
  margin: 0 auto;
}
.price {
  color: red;
  font-size: 18px;
  font-weight: 600;
}
</style>